<template>
	<navBar title="头像与用户名"></navBar>
	<view>
		<!-- 头像选择按钮 -->
		<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
			<image class="avatar" :src="avatarUrl"></image>
		</button>

		<!-- 昵称输入框 -->
		<input type="nickname" class="weui-input" placeholder="请输入昵称" v-model="nickName" @blur="onNicknameBlur">

		<button class="confirm" @click="save">确认</button>
	</view>
	<tabBar></tabBar>
</template>

<script>
	import {
		userInfo
	} from '@/stores/userInfo'

	export default {
		data() {
			return {
				avatarUrl: '',
				nickName: ''
			}
		},

		onLoad() {
			this.avatarUrl = userInfo().avatarUrl
			this.nickName = userInfo().nickName
		},

		methods: {
			// 微信小程序选择头像
			onChooseAvatar(e) {
				this.avatarUrl = e.detail.avatarUrl
			},

			// 保存昵称
			onNicknameBlur(e) {
				this.nickName = e.detail.value
			},

			// 一键保存
			async save() {
				if (this.avatarUrl === '' || this.nickName === '') {
					uni.showToast({
						title: '不能为空',
						icon: 'error'
					})
					return
				}
				await userInfo().changeIdentity(this.avatarUrl, this.nickName)
				console.log('测试:', this.avatarUrl)
				uni.showToast({
					title: '修改成功'
				})
			}
		}
	}
</script>

<style scoped>
	.avatar-wrapper {
		width: 100rpx;
		height: 100rpx;
		border-radius: 50%;
		overflow: hidden;
		margin: 20px auto;
		padding: 0%;
		position: relative;
	}

	.avatar {
		width: 100%;
		height: 100%;
		border-radius: 50%;
	}

	.weui-input {
		width: 80%;
		margin: 20px auto;
		padding: 10px;
		border: 1px solid #eee;
		border-radius: 4px;
	}
</style>